from machine import Pin
import utime
import network
import usocket

# SSID信息
ssid = "Redmi K60 Ultra"
pwd = "24361234"

# socket配置
dest_ip = "192.168.207.58"
dest_port = 5566

# LED提示灯
led = Pin(16, Pin.OUT, value=0)


def wifi_connect():
    global ssid, pwd
    
    # 创建WLAN对象
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    # 建立wifi连接
    start_time = utime.time()
    
    if not wlan.isconnected():
        print("正在连接路由器...")
        wlan.connect(ssid, pwd)
        
        while True:
            led.value(1)
            utime.sleep_ms(250)
            led.value(0)
            utime.sleep_ms(250)
            if wlan.isconnected():
                print("WLAN config: ", wlan.ifconfig())
                return True
            elif utime.time() - start_time > 15:
                print("连接超时...")
                return False 
    else:
        led.value(0)
        print("WLAN config: ", wlan.ifconfig())
        return True


if __name__ == "__main__":
    
    if wifi_connect():
        # 创建socket对象
        socket = usocket.socket()
        addr = (dest_ip, dest_port)
        socket.connect(addr)
        # 发送信息
        socket.send("Hello socket")
        
        while True:
            # 接收信息
            text = socket.recv(128)
            if not text:
                pass
            else:
                print(text.decode("utf-8"))
                socket.send("get: " + text.decode("utf-8"))
            utime.sleep_ms(300)
        
    

